package com.group.sliding.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.sliding.context.UserContext;
import com.group.sliding.domain.dto.CartFormDTO;
import com.group.sliding.domain.po.Cart;
import com.group.sliding.domain.vo.CartVO;
import com.group.sliding.exception.BizIllegalException;
import com.group.sliding.mapper.CartMapper;
import com.group.sliding.service.ICartService;
import com.group.sliding.utils.BeanUtils;
import com.group.sliding.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 订单详情表 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Override
    public void addItem2Cart(CartFormDTO cartFormDTO) {
        Long userId = UserContext.getUser();
        Long itemId = cartFormDTO.getItemId();
        LocalDateTime now = LocalDateTime.now();
        // 判断是否已经存在
        Cart dbCart = lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getItemId, itemId)
                .one();
        if(dbCart != null) {
            // 存在，则更新数量
            dbCart.setNum(dbCart.getNum() + 1);
            dbCart.setUpdateTime(now);
            updateById(dbCart);
            return;
        }
        // 不存在，判断是否超过购物车数量
        Long count = lambdaQuery().eq(Cart::getUserId, userId).count();
        if (count >= 10) {
            throw new BizIllegalException(StrUtil.format("用户购物车不同商品数量不能超过{}", 10));
        }

        // 新增购物车条目
        Cart cart = BeanUtils.copyBean(cartFormDTO, Cart.class);
        cart.setUserId(userId);
        cart.setNum(1);
        cart.setCreateTime(now);
        cart.setUpdateTime(now);
        save(cart);
    }

    @Override
    public List<CartVO> queryMyCarts() {
        // 查询我的购物车列表
        List<Cart> carts = lambdaQuery().eq(Cart::getUserId, UserContext.getUser()).list();
        if (CollUtils.isEmpty(carts)) {
            return CollUtils.emptyList();
        }
        return BeanUtils.copyList(carts, CartVO.class);
    }

    @Override
    public void removeByItemIds(Collection<Long> itemIds) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<Cart>();
        queryWrapper.lambda()
                .eq(Cart::getUserId, UserContext.getUser())
                .in(Cart::getItemId, itemIds);
        remove(queryWrapper);
    }
}
